package com.itheima.interceptor;

import com.itheima.utils.JwtUtils;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

//@Component
public class TokenInterceptor implements HandlerInterceptor {
    private static final Logger log = LoggerFactory.getLogger(TokenInterceptor.class);
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String requestURI = request.getRequestURI();

        if (requestURI.contains("/login")){
            log.info("登录操作，放行...");
            return true;
        }

        String token = request.getHeader("token");

        if (token == null || token.isEmpty()){
            log.info("请求头中不包含token，返回401...");

            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);

            return false;
        }

        try{
            log.info("请求头中包含token，进行解析...");
            JwtUtils.parseToken(token);
        }catch (Exception e){
            log.info("解析token失败，返回401...");
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            return false;
        }

        log.info("token有效，放行...");
        return true;
    }
}
